package com.baidu.logindemos.ui.main

import com.baidu.logindemos.R
import com.baidu.logindemos.db.model.IUserModelImpl
import com.baidu.logindemos.db.model.SharedPreferencesUtil

class ILoginPresenterImpl private constructor(val mView: ILoginView): ILoginPresenter,IRepository {
    private var name:String? = null
    private var password:String? = null
    private var isPasswordType = 0
    private val mUserModel = IUserModelImpl.getInstance(this)

    companion object {
        //自己封装创建自己的方法
        //外部无法直接创建
        //十分安全
        fun getInstance(view: ILoginView): ILoginPresenter{
            return ILoginPresenterImpl(view)
        }
    }

    override fun login() {
        val user = mUserModel.getUser(name!!)
        if (user == null){
            mView.showError("用户不存在")
        }else{
            if (user.password == password){
                mView.showOK()
            }else{
                mView.showError("密码错误")
            }
        }
    }

    override fun nameChanged(name: String) {
        this.name = name
        checkStatus()
    }

    override fun passwordChanged(password: String) {
        this.password = password
        checkStatus()
    }

    override fun eyeClicked() {
        if (isPasswordType == 0){
            isPasswordType = 1
            mView.changeEyeResource(R.drawable.eye,false)
        }else{
            isPasswordType = 0
            mView.changeEyeResource(R.drawable.eye_close,true)
        }
    }

    private fun checkStatus(){
        var enabled = false
        if (name == null || password == null) {
            enabled = false
        } else{
            if (name!!.isNotEmpty() && password!!.isNotEmpty()) {
                enabled = true
            }else{
                enabled = false
            }
        }
        mView.changeBtnEnableStatus(enabled)
    }

    override fun saveOk() {

    }

    override fun saveFailure() {

    }
}